﻿$(function () {
    $('.icon-checked').click(function () {
        if ($(this).closest('li').attr('class') == 'icon-checked') {
            $(this).closest('li').removeClass("icon-checked");
            $(this).closest('li').addClass("icon-unchecked");
        }
        else {
            $(this).closest('li').removeClass("icon-unchecked");
            $(this).closest('li').addClass("icon-checked");
        }
    });

    $('.icon-unchecked').click(function () {
        if ($(this).closest('li').attr('class') == 'icon-unchecked') {
            $(this).closest('li').removeClass("icon-unchecked");
            $(this).closest('li').addClass("icon-checked");
        }
        else {
            $(this).closest('li').removeClass("icon-checked");
            $(this).closest('li').addClass("icon-unchecked");
        }
    });

    $('#btnSave').click(function () {
        SaveSelectedItems();
    });

    $('#btnClear').click(function () {
        ClearItems();
    });

    $("#idP1").tabs();
    $("#idP2").tabs();

    //*******************************************
    $('.item-del').live('click', function () {
        if (confirm('¿Esta seguro que desea eliminar el registro?')) {
            $(this).closest('li').remove();
        }
    });

    // Historia de Dolor    
    $('#txttimeofDay').timepicker({
        timeFormat: 'hh:mm tt',
        stepHour: 1,
        stepMinute: 10
    });

    // Antecedentes Quirurgicos
    $("#txtDateAntecedentSurgical").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    // Examenes de Laboratorio
    $("#txtDateExamLaboratory").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });
    //*************************************************

    $("#txtdentistVisitsFrequency").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtlastVisit").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtlastRadiography").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtreceivedTreatment").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    // validaciones 
    $("#frmAntecedentAllergic").bind("invalid-form.validate", function () {        
    }).validate({
        debug: true,
        rules: {            
            txtMedicineORFoodAntecedentAllergic: {
                required: true,
                minlength: 250
            },
            txtClinicalManifestationsAntecedentAllergic: {
            required: true,
            minlength: 250
            }
        },
        messages: {            
            txtMedicineORFoodAntecedentAllergic: "Medicamento o Alimento es requerida",
            txtClinicalManifestationsAntecedentAllergic: "Manifestaciones Clínicas es requerida"
        }
    });

});

// medicineORFood, clinicalManifestations, precaution, observation
function AddAntecedentAllergic() {    
    //if ($("#frmAntecedentAllergic").valid()) {
        var medicineORFood = $('#txtMedicineORFoodAntecedentAllergic').val();
        var clinicalManifestations = $('#txtClinicalManifestationsAntecedentAllergic').val();
        var precautionString = $('#txtPrecautionAntecedentAllergic').is(':checked') ? 'SI' : 'NO';
        var precautionBool = $('#txtPrecautionAntecedentAllergic').is(':checked') ? true : false;
        var observation = $('#txtObservationAntecedentAllergic').val();

        var item = "";
        item = "<li medicineORFood='" + medicineORFood + "' clinicalManifestations='" + clinicalManifestations + "' precaution='" + precautionBool + "' observation='" + observation + "'>" +
                "<table style='width: 100%;'>" +
                    "<tr>" +
                        "<td style='width: 25%; text-align: left;'>" + medicineORFood + "</td>" +
                        "<td style='width: 25%; text-align: left;'>" + clinicalManifestations + "</td>" +
                        "<td style='width: 10%; text-align: left;'>" + precautionString + "</td>" +
                        "<td style='width: 40%; text-align: left;'>" + observation + "</td>" +
                        "<td></td>" +
                    "</tr>" +
                 "</table>" +
                 "<img class='item-del' width='16' height='16' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' style='float: right; vertical-align: middle; margin-top: -15px; margin-left: 15px; cursor: pointer; border: 0px;'>" +
                 "</li>";
        $("#ulAntecedentAllergicList").append(item);
        clearAntecedentAllergicForm();  
    //}    
}

function clearAntecedentAllergicForm() {
    $('#txtLocalizarionEncargado').val('');
    $('#txtMedicineORFoodAntecedentAllergic').val('');
    $('#txtClinicalManifestationsAntecedentAllergic').val('');
    $('#txtPrecautionAntecedentAllergic').attr('checked', false);
    $('#txtObservationAntecedentAllergic').val('');
}

function AddAntecedentSurgical() {
    var process = $('#txtProcessAntecedentSurgical').val();
    var medicalCenter = $('#txtMedicalCenterAntecedentSurgical').val();
    var precautionString = $('#boolPrecautionAntecedentSurgical').is(':checked') ? 'SI' : 'NO';
    var precautionBool = $('#boolPrecautionAntecedentSurgical').is(':checked') ? true : false;
    var dateAntecedentSurgical = $('#txtDateAntecedentSurgical').val();   
    
    var item = "";
    item = "<li process='" + process + "' medicalCenter='" + medicalCenter + "' precaution='" + precautionBool + "' dateAntecedentSurgical='" + dateAntecedentSurgical + "'>" +
            "<table style='width: 100%;'>" +
                "<tr>" +
                    "<td style='width: 25%; text-align: left;'>" + process + "</td>" +
                    "<td style='width: 25%; text-align: left;'>" + medicalCenter + "</td>" +
                    "<td style='width: 10%; text-align: left;'>" + precautionString + "</td>" +
                    "<td style='width: 40%; text-align: left;'>" + dateAntecedentSurgical + "</td>" +
                    "<td></td>" +
                "</tr>" +
             "</table>" +
             "<img class='item-del' width='16' height='16' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' style='float: right; vertical-align: middle; margin-top: -15px; margin-left: 15px; cursor: pointer; border: 0px;'>" +
             "</li>";
    $("#ulAntecedentSurgicalList").append(item);
    clearAntecedentSurgical();
}

function clearAntecedentSurgical() {
    $('#txtProcessAntecedentSurgical').val('');
    $('#txtMedicalCenterAntecedentSurgical').val('');
    $('#boolPrecautionAntecedentSurgical').attr('checked', false);
    $('#txtDateAntecedentSurgical').val('');    
}

function AddMedicament() {
    var name = $('#txtNameMedicament').val();
    var dose = $('#txtDoseMedicament').val();    
    var precautionString = $('#boolPrecautionMedicament').is(':checked') ? 'SI' : 'NO';
    var precautionBool = $('#boolPrecautionMedicament').is(':checked') ? true : false;
    var observation = $('#txtObservationMedicament').val();

    var item = "";
    item = "<li name='" + name + "' dose='" + dose + "' precaution='" + precautionBool + "' observation='" + observation + "'>" +
            "<table style='width: 100%;'>" +
                "<tr>" +
                    "<td style='width: 25%; text-align: left;'>" + name + "</td>" +
                    "<td style='width: 25%; text-align: left;'>" + dose + "</td>" +
                    "<td style='width: 10%; text-align: left;'>" + precautionString + "</td>" +
                    "<td style='width: 40%; text-align: left;'>" + observation + "</td>" +
                    "<td></td>" +
                "</tr>" +
             "</table>" +
             "<img class='item-del' width='16' height='16' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' style='float: right; vertical-align: middle; margin-top: -15px; margin-left: 15px; cursor: pointer; border: 0px;'>" +
             "</li>";
    $("#ulMedicamentList").append(item);
    clearMedicament();
}

function clearMedicament() {
    $('#txtNameMedicament').val('');
    $('#txtDoseMedicament').val('');
    $('#boolPrecautionMedicament').attr('checked', false);
    $('#txtObservationMedicament').val('');
}

function AddExamLaboratory() {
    var type = $('#txtTypeExamLaboratory').val();
    var dateExamLaboratory = $('#txtDateExamLaboratory').val();
    var result = $('#txtResultExamLaboratory').val();    
    var precautionString = $('#boolPrecautionExamLaboratory').is(':checked') ? 'SI' : 'NO';
    var precautionBool = $('#boolPrecautionExamLaboratory').is(':checked') ? true : false;
    var observation = $('#txtObservationExamLaboratory').val();

    var item = "";
    item = "<li type='" + type + "' dateExamLaboratory='" + dateExamLaboratory + "' result='" + result + "' precaution='" + precautionBool + "' observation='" + observation + "'>" +
            "<table style='width: 100%;'>" +
                "<tr>" +
                    "<td style='width: 20%; text-align: left;'>" + type + "</td>" +
                    "<td style='width: 20%; text-align: left;'>" + dateExamLaboratory + "</td>" +
                    "<td style='width: 10%; text-align: left;'>" + result + "</td>" +
                    "<td style='width: 10%; text-align: left;'>" + precautionString + "</td>" +
                    "<td style='width: 40%; text-align: left;'>" + observation + "</td>" +
                    "<td></td>" +
                "</tr>" +
             "</table>" +
             "<img class='item-del' width='16' height='16' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' style='float: right; vertical-align: middle; margin-top: -15px; margin-left: 15px; cursor: pointer; border: 0px;'>" +
             "</li>";
    $("#ulExamLaboratoryList").append(item);
    clearExamLaboratory();
}

function clearExamLaboratory() {
    $('#txtTypeExamLaboratory').val('');
    $('#txtDateExamLaboratory').val('');
    $('#txtResultExamLaboratory').val('');
    $('#boolPrecautionExamLaboratory').attr('checked', false);
    $('#txtObservationExamLaboratory').val('');    
}

function AddAntecedentPathologicalFamily() {
    var kinship = $('#txtKinshipAntecedentPathologicalFamily').val();
    var diseaseCondition = $('#txtDiseaseConditionAntecedentPathologicalFamily').val();    
    var precautionString = $('#boolPrecautionAntecedentPathologicalFamily').is(':checked') ? 'SI' : 'NO';
    var precautionBool = $('#boolPrecautionAntecedentPathologicalFamily').is(':checked') ? true : false;
    var observation = $('#txtObservationAntecedentPathologicalFamily').val();

    var item = "";
    item = "<li kinship='" + kinship + "' diseaseCondition='" + diseaseCondition + "' precaution='" + precautionBool + "' observation='" + observation + "'>" +
            "<table style='width: 100%;'>" +
                "<tr>" +
                    "<td style='width: 25%; text-align: left;'>" + kinship + "</td>" +
                    "<td style='width: 25%; text-align: left;'>" + diseaseCondition + "</td>" +                    
                    "<td style='width: 10%; text-align: left;'>" + precautionString + "</td>" +
                    "<td style='width: 40%; text-align: left;'>" + observation + "</td>" +
                    "<td></td>" +
                "</tr>" +
             "</table>" +
             "<img class='item-del' width='16' height='16' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' style='float: right; vertical-align: middle; margin-top: -15px; margin-left: 15px; cursor: pointer; border: 0px;'>" +
             "</li>";
    $("#ulAntecedentPathologicalFamilyList").append(item);
    clearAntecedentPathologicalFamily();
}

function clearAntecedentPathologicalFamily() {
    $('#txtKinshipAntecedentPathologicalFamily').val('');
    $('#txtDiseaseConditionAntecedentPathologicalFamily').val('');
    $('#txtObservationAntecedentPathologicalFamily').val('');    
    $('#boolPrecautionAntecedentPathologicalFamily').attr('checked', false);    
}

//*****************************************************************************************************************
function SaveSelectedItems() {
    
    // *** Datos Personales **************************************
    var chkMedic = $('#chkMedic').is(':checked') ? true : false;
    var txtdisease = $('#txtdisease').val();
    var txtdiseaseHistory = $('#txtdiseaseHistory').val();
    var cmbBloodTypeID = $('#cmbBloodTypeID').val();
    var txtpulse = $('#txtpulse').val();
    var chkindPulseWarning = $('#chkindPulseWarning').is(':checked') ? true:false;
    var txtbloodPressure = $('#txtbloodPressure').val();
    var chkindbloodPressureWarning = $('#chkindbloodPressureWarning').is(':checked') ? true:false;
    var txtrespiratoryFrequency = $('#txtrespiratoryFrequency').val();
    var chkindRespiratoryFrequencyWarning = $('#chkindRespiratoryFrequencyWarning').is(':checked') ? true:false;
    var txttemperature = $('#txttemperature').val();
    var chkindTemperatureWarning = $('#chkindTemperatureWarning').is(':checked') ? true:false;
    var txtglycemia = $('#txtglycemia').val();
    var chkindGlycemiaWarning = $('#chkindGlycemiaWarning').is(':checked') ? true:false;
    var txtheight = $('#txtheight').val();
    var txtweight = $('#txtweight').val();
    var chkindWeightWarning = $('#chkindWeightWarning').is(':checked') ? true:false;   
    
    // ***********************************************************
    // Antecedentes patológicos
    var values = new Array();
    var result = new Array();
    
    var categories = $("#pnlRight .tabs-content").find(".colx3-left").find(".icon-checked");
    var warnings = $("#pnlRight .tabs-content").find(".colx3-center").find(".icon-checked");
    var comments = $("#pnlRight .tabs-content").find(".colx3-right").find(".full-width");
    
    for (var i = 0; i < categories.length; i++) {
        var id = categories[i].id;
        values.push(id);
        result.push(id + ";true;false;");
    }
    
    for (var i = 0; i < warnings.length; i++) {
        var id = warnings[i].id.replace('idPD', '');
        var searchIndex = values.indexOf(id);
        if (searchIndex >= 0) {
            var item = id + ";true;true;";
            result[searchIndex] = item;
        }
        else {
            values.push(id);
            result.push(id + ";false;true;");
        }
    }
    
    for (var i = 0; i < comments.length; i++) {
        if (comments[i].value != '') {
            var id = comments[i].id.replace('txt', '');
            var comment = comments[i].value;
            var searchIndex = values.indexOf(id);
            if (searchIndex >= 0) {
                var item = result[searchIndex] + comment;
                result[searchIndex] = item;
            }
            else {
                values.push(id);
                result.push(id + ";false;false;" + comment);
            }
        }
    }
    
    // ***********************************************************
    // Historia de Dolor
    var cmblocation = $('#cmblocation').val();
    var cmbchronology = $('#cmbchronology').val();
    var cmbfrequency = $('#cmbfrequency').val();
    var cmbintensity = $('#cmbintensity').val();
    var cmbgrade = $('#cmbgrade').val();
    
    var chkindPreviousTreatment = $('#chkindPreviousTreatment').is(':checked') ? true:false;
    var chkindHeat = $('#chkindHeat').is(':checked') ? true:false;
    var chkindCold = $('#chkindCold').is(':checked') ? true:false;
    var chkindSweet = $('#chkindSweet').is(':checked') ? true : false;
    var chkindBite = $('#chkindBite').is(':checked') ? true : false;
    var chkindPercussion = $('#chkindPercussion').is(':checked') ? true : false;
    var indPalpation = $('#indPalpation').is(':checked') ? true : false;
    var indHeadPosition = $('#indHeadPosition').is(':checked') ? true : false;
    var txttimeofDay = $('#txttimeofDay').val();
    var txttother = $('#txttother').val();
    var chkindAttenuatingFactor = $('#chkindAttenuatingFactor').is(':checked') ? true : false;
    
    // ***********************************************************
    // Antecedentes alérgicos
    var ulAntecedentAllergicList = $('#ulAntecedentAllergicList li');    
    var antecedentAllergicArray = new Array();
    ulAntecedentAllergicList.each(function () {
        var current = $(this);        
        var item = current.attr("medicineORFood") + ";" + current.attr("clinicalManifestations") + ";" + current.attr("precaution") + ";" + current.attr("observation") + ";";        
        antecedentAllergicArray.push(item);
    });
    
    // ***********************************************************
    // Antecedentes quirúrjicos
    var ulAntecedentSurgicalList = $('#ulAntecedentSurgicalList li');
    var antecedentSurgicalArray = new Array();
    ulAntecedentSurgicalList.each(function () {
        var current = $(this);
        var item = current.attr("process") + ";" + current.attr("medicalCenter") + ";" + current.attr("precaution") + ";" + current.attr("dateAntecedentSurgical") + ";";
        antecedentSurgicalArray.push(item);
    });
    
    // ***********************************************************
    // Medicamentos
    var ulMedicamentList = $('#ulMedicamentList li');
    var medicamentArray = new Array();
    ulMedicamentList.each(function () {
        var current = $(this);
        var item = current.attr("name") + ";" + current.attr("dose") + ";" + current.attr("precaution") + ";" + current.attr("observation") + ";";
        medicamentArray.push(item);
    });
    
    // ***********************************************************
    // Exámenes de laboratorio
    var ulExamLaboratoryList = $('#ulExamLaboratoryList li');
    var examLaboratoryArray = new Array();
    ulExamLaboratoryList.each(function () {
        var current = $(this);
        var item = current.attr("type") + ";" + current.attr("dateExamLaboratory") + ";" + current.attr("result") + ";" + current.attr("precaution") + ";" + current.attr("observation") + ";";
        examLaboratoryArray.push(item);
    });
    
    // ***********************************************************
    // Antecedentes patológicos familiares
    var ulAntecedentPathologicalFamilyList = $('#ulAntecedentPathologicalFamilyList li');
    var antecedentPathologicalFamilyArray = new Array();
    ulAntecedentPathologicalFamilyList.each(function () {
        var current = $(this);
        var item = current.attr("kinship") + ";" + current.attr("diseaseCondition") + ";" + current.attr("precaution") + ";" + current.attr("observation") + ";";
        antecedentPathologicalFamilyArray.push(item);
    });
    
    // ***********************************************************
    // Historia social
    var cmbmaritalStatusID = $('#cmbmaritalStatusID').val();
    var txtnumberOfChildren = $('#txtnumberOfChildren').val();
    var txthabits = $('#txthabits').val();
    var txteducation = $('#txteducation').val();
    var txtjobType = $('#txtjobType').val();
    var txtavailability = $('#txtavailability').val();
    
    // ***********************************************************
    // Historia Dental
    var txtdentistVisitsFrequency = $('#txtdentistVisitsFrequency').val();
    var txtlastVisit = $('#txtlastVisit').val();
    var txtlastRadiography = $('#txtlastRadiography').val();
    var txtreceivedTreatment = $('#txtreceivedTreatment').val();
    var txtoralHygieneTechnique = $('#txtoralHygieneTechnique').val();
    var txttoothpaste = $('#txttoothpaste').val();
    var txttoothbrush = $('#txttoothbrush').val();
    var txtdentalFloss = $('#txtdentalFloss').val();
    var chkindLocalAnestheticReaction = $('#chkindLocalAnestheticReaction').is(':checked') ? true : false;
    var txtcomments = $('#txtcomments').val();
    var chkprecautionAnestheticReaction = $('#chkprecautionAnestheticReaction').is(':checked') ? true : false;
    // ***********************************************************

    if (result.length > 0) {
        $.ajax(
        {
            type: "POST",
            traditional: true,
            url: $("#urlSave").val(),
            secureuri: false,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            enctype: 'multipart/form-data',
            data:
                JSON.stringify({
                    personID: $("#PersonID").val(),                    
                    values: result,                    
                    indMedic: chkMedic,
                    disease: txtdisease,
                    diseaseHistory: txtdiseaseHistory,
                    bloodTypeID: cmbBloodTypeID,
                    pulse: txtpulse,
                    indPulseWarning: chkindPulseWarning,
                    bloodPressure: txtbloodPressure,
                    indbloodPressureWarning: chkindbloodPressureWarning,
                    respiratoryFrequency: txtrespiratoryFrequency,
                    indRespiratoryFrequencyWarning: chkindRespiratoryFrequencyWarning,
                    temperature: txttemperature,                    
                    indTemperatureWarning: chkindTemperatureWarning,
                    glycemia: txtglycemia,
                    indGlycemiaWarning: chkindGlycemiaWarning,
                    height: txtheight,
                    weight: txtweight,
                    indWeightWarning: chkindWeightWarning,        
                    location: cmblocation,
                    chronology: cmbchronology,
                    frequency: cmbfrequency,
                    intensity: cmbintensity,                    
                    grade: cmbgrade,
                    indPreviousTreatment: chkindPreviousTreatment,         
                    indHeat: chkindHeat,
                    indCold: chkindCold,
                    indSweet: chkindSweet,
                    indBite: chkindBite,
                    indPercussion: chkindPercussion,
                    indPalpation: indPalpation,
                    indHeadPosition: indHeadPosition,
                    timeofDay: txttimeofDay,                    
                    other: txttother,                    
                    indAttenuatingFactor: chkindAttenuatingFactor,
                    antecedentAllergicArray: antecedentAllergicArray,
                    antecedentSurgicalArray: antecedentSurgicalArray,
                    medicamentArray: medicamentArray,
                    examLaboratoryArray: examLaboratoryArray,
                    antecedentPathologicalFamilyArray: antecedentPathologicalFamilyArray,        
                    maritalStatusID: cmbmaritalStatusID,
                    numberOfChildren: txtnumberOfChildren,
                    habits: txthabits,                    
                    education: txteducation,                    
                    jobType: txtjobType,                    
                    availability: txtavailability,
                    dentistVisitsFrequency: txtdentistVisitsFrequency,
                    lastVisit: txtlastVisit,
                    lastRadiography: txtlastRadiography,
                    receivedTreatment: txtreceivedTreatment,
                    oralHygieneTechnique: txtoralHygieneTechnique,
                    toothpaste: txttoothpaste,
                    toothbrush: txttoothbrush,                    
                    dentalFloss: txtdentalFloss,
                    indLocalAnestheticReaction: chkindLocalAnestheticReaction,
                    comments: txtcomments,
                    precautionAnestheticReaction: chkprecautionAnestheticReaction                    
                                        
                }),
            success: function (data, status) {    
                if (data.success) {
                    $("#lblMsg").removeClass("error");
                    $("#lblMsg").addClass("success");
                    $("#txtMsg").text("Los elementos se han guardado correctamente");
                    $("#lblMsg").show(300).delay(5000).hide(400);
                }
                else {
                    $("#lblMsg").removeClass("success");
                    $("#lblMsg").addClass("error");
                    $("#txtMsg").text(data.Msg);
                    $("#lblMsg").show(300).delay(5000).hide(400);
                }
            },
            error: function (data, status, e) {
                alert(e);
            }
        });
    }
    else {
        $("#lblMsg").removeClass("success");
        $("#lblMsg").addClass("error");
        $("#txtMsg").text('Debe seleccionar al menos un elemento');
        $("#lblMsg").show(300).delay(5000).hide(400);
    }
}

function ClearItems() {
    var comments = $("#pnlRight .tabs-content").find(".colx3-right").find(".full-width");
    for (var i = 0; i < comments.length; i++) {
        comments[i].value = '';
    }

    $(".icon-checked").each(function () {
        $(this).closest('li').removeClass("icon-checked");
        $(this).closest('li').addClass("icon-unchecked");
    });
}